import { useIntersectionObserver, useMouseInElement, useIntervalFn   } from '@vueuse/core'
import { reactive, ref, watch, onUnmounted } from 'vue'
import axios from 'axios'
// 数据懒加载函数
export const useLazyData = (apiFn) => {
  const target = ref(null)
  const result = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if(isIntersecting){
        stop()
        apiFn().then(data => {
          result.value = data.result
        })
      }
    },
    {
      threshold: 0
    }
  )
  return { target, result }
}

// 获取鼠标偏移量
export const usePreviewImg = () => {
  const target = ref(null)
  const show = ref(false)
  // elementX 鼠标基于容器左上角X轴偏移
  // elementY 鼠标基于容器左上角Y轴偏移
  // isOutside 鼠标是否在模板容器外
  const { elementX, elementY, isOutside } = useMouseInElement(target)
  const position = reactive({ left: 0, top: 0 })
  const bgPosition = reactive({ backgroundPositionX: 0, backgroundPositionY: 0 })
  watch([elementX, elementY, isOutside], () => {
    // 控制X轴方向的定位 0-200 之间
    if (elementX.value < 100) position.left = 0
    else if (elementX.value > 300) position.left = 200
    else position.left = elementX.value - 100
    // 控制Y轴方向的定位 0-200 之间
    if (elementY.value < 100) position.top = 0
    else if (elementY.value > 300) position.top = 200
    else position.top = elementY.value - 100
    // 设置大背景的定位
    bgPosition.backgroundPositionX = -position.left * 2 + 'px'
    bgPosition.backgroundPositionY = -position.top * 2 + 'px'
    // 设置遮罩容器的定位
    position.left = position.left + 'px'
    position.top = position.top + 'px'
    // 设置是否显示预览大图
    show.value = !isOutside.value
  })
  return { position, bgPosition, show, target }
}


// 获取城市数据
export const getCityData = async () => {
  const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
  const res = await axios(url)
  return res.data
}

// 提供倒计时
export const usePayTime = () => {
  const time = ref(0)
  const timeText = ref('')
  const { pause, resume } = useIntervalFn(()=>{
    time.value--
    timeText.value = `${parseInt(time.value/60)}分${time.value%60}秒`
    if(time.value <= 0){
      timeText.value = '已截止'
      pause()
    }
  }, 1000, false)
  onUnmounted(() => {
    pause()
  })
  // 开启倒计时
  const start = (countdown) => {
    time.value = countdown
    timeText.value = `${parseInt(time.value/60)}分${time.value%60}秒`
    resume()
  }
  return {
    start,
    timeText
  }
}
